<template>
    <div>
        <el-card style="width: 100%;margin: 0;" shadow="always">
            <template #header>
                <el-form :inline="true" :model="findForm" class="demo-form-inline">
                    <el-form-item label="用户名：">
                        <el-input v-model="findForm.userName" placeholder="请输入用户名" style="width: 200px" clearable />
                    </el-form-item>
                    <el-form-item label="工作单位：">
                        <el-input v-model="findForm.job" placeholder="请输入工作单位" style="width: 200px" clearable />
                    </el-form-item>
                    <el-form-item label="角色">
                        <el-select v-model="findForm.roleId" placeholder="请选择..." style="width: 200px" clearable>
                            <el-option v-for="item in roleArr" :key="item.id" :label="item.userRole"
                                :value="item.userRole">
                                <span style="float: left">{{ item.userRole }}</span>
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="initUserForm(findForm)">查询</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="success" @click="AddUser()">添加项目</el-button>
                    </el-form-item>
                </el-form>
            </template>
            <el-table :data="userArr" style="width: 100%" max-height="800"
                :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }">
                <el-table-column type="index" width="50" />
                <el-table-column property="avatarUrl" label="头像" width="110">
                    <template #default="scope">
                        <div>
                            <el-image v-if="scope.row.avatarUrl" style="width: 100px; height: 100px"
                                :src="scope.row.avatarUrl" :preview-src-list="[scope.row.avatarUrl]" fit="fill" />
                        </div>
                    </template>
                </el-table-column>
                <el-table-column property="account" label="账号（工号 || 学号）" width="300" />
                <el-table-column property="password" label="密码" width="300" />
                <el-table-column property="userName" label="用户名" width="80" />
                <el-table-column property="job" label="工作单位（学校）" width="80" />
                <el-table-column property="roleId" label="角色" width="80" />
                <el-table-column property="lastIp" label="IP地址" width="80" />
                <el-table-column property="addTime" label="创建日期" width="120" />
                <el-table-column property="updateTime" label="修改日期" width="120" />
                <el-table-column label="操作" width="200">
                    <template #default="scope">
                        <el-button key="primary" type="primary" @click="UpdateUser(scope.row)">修改</el-button>
                        <el-button key="danger" type="danger" @click="deleteUserById(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
    </div>
    <!-- 添加和修改操作 -->
    <el-drawer v-model="drawerForm" :title="drawerTitle" direction="rtl" size="30%">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="userForm" :rules="rules" label-width="auto"
            class="demo-ruleForm" status-icon>
            <el-form-item label="项目图片" prop="avatarUrl">
                <el-upload class="avatar-uploader" active="#" :limit="1" :show-file-list="false"
                    :before-upload="beforeAvatarUpload" :http-request="handleFileUpload">
                    <el-image v-if="userForm.avatarUrl" style="width: 100px; height: 100px" :src="userForm.avatarUrl"
                        :preview-src-list="[userForm.avatarUrl]" fit="fill" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="学号 || 工号：" prop="account">
                <el-input v-model="userForm.account" />
            </el-form-item>
            <el-form-item label="密码：" prop="password">
                <el-input v-model="userForm.password" />
            </el-form-item>
            <el-form-item label="用户名" prop="userName">
                <el-input v-model="userForm.userName" />
            </el-form-item>
            <el-form-item label="工作单位" prop="job">
                <el-input v-model="userForm.job" />
            </el-form-item>
            <el-form-item label="角色" prop="roleId">
                <el-select v-model="userForm.roleId" placeholder="请选择角色">
                    <el-option v-for="item in roleArr" :key="item.id" :label="item.userRole" :value="item.id">
                        <span style="float: left">{{ item.userRole }}</span>
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="addOrUpdateUser({ title: drawerTitle, data: userForm })">
                    提交
                </el-button>
                <el-button @click="drawerForm = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-drawer>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
// element-plus导入组件
import { ElMessage, ElNotification } from 'element-plus';
import type { FormInstance, FormRules, UploadProps } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
// 后端接口
import { Upload } from '../../api/upload';
import { findAllUser, updateUser, addUser, deleteUser } from '../../api/user';
import { FindAllRole, GetRoleId } from '../../api/role';

import dayjs from "dayjs";
// 页面跳转
import { useRouter } from 'vue-router';
const router = useRouter();
const errorId = sessionStorage.getItem('userRoleId')+''
if(errorId == undefined || errorId == '' || (errorId != '999' && errorId != '20')){
    sessionStorage.setItem('error','not')
    router.push("/LimitsAuthority")
}


// 查询信息参数
const findForm = reactive({
    userName: '',
    job: '',
    roleId: '',
})
// 角色信息
const roleArr = ref([] as any[]);
const initRole = () => {
    FindAllRole({}).then((res: any) => {
        roleArr.value = res.data;
    })
}
initRole()
// 用户信息
const userArr = ref([] as any[]);
const initUserForm = (findForm: any) => {
    findAllUser(findForm).then((res: any) => {
        if (res.code == 2000) {
            userArr.value = res.data;
            userArr.value.forEach((item: any) => {
                item.addTime = dataFormat(item.addTime);
                item.updateTime = dataFormat(item.updateTime);
                GetRoleId({ id: item.roleId }).then((res: any) => {
                    item.roleId = res.data.userRole;
                })
            })

        }
    })
}
initUserForm(findForm);
// 抽屉参数
const drawerForm = ref(false)
const drawerTitle = ref('')
const openDrawer = (drawerData: string) => {
    drawerForm.value = true
    drawerTitle.value = drawerData
}
// 添加和修改操作
const AddUser = () => {
    openDrawer('添加用户信息')
    userForm.id = 0
    userForm.avatarUrl = ""
    userForm.account = ""
    userForm.password = ""
    userForm.userName = ""
    userForm.job = ""
    userForm.roleId = ""
}
const UpdateUser = (data: any) => {
    openDrawer('修改用户信息')
    userForm.id = data.id
    userForm.avatarUrl = data.avatarUrl
    userForm.account = data.account
    userForm.password = data.password
    userForm.userName = data.userName
    userForm.job = data.job
    userForm.roleId = data.roleId
}
const addOrUpdateUser = (data: any) => {
    console.log(data);
    if (!ruleFormRef.value) return;
    ruleFormRef.value.validate((valid: boolean) => {
        if (valid) {
            console.log('表单提交成功');
            // 处理添加或更新逻辑
            if (data.title === '添加用户信息') {
                addUser(data.data).then((res: any) => {
                    if (res.code == 2000) {
                        ElNotification({
                            title: '成功',
                            message: '添加成功',
                            type: 'success',
                        });
                        drawerForm.value = false;
                        initUserForm(findForm);
                    } else {
                        ElMessage.error(res.message);
                    }
                });
            } else if (data.title === '修改用户信息') {
                console.log(data.data);
                updateUser(data.data).then((res: any) => {
                    if (res.code == 2000) {
                        ElNotification({
                            title: '成功',
                            message: '修改成功',
                            type: 'success',
                        });
                        drawerForm.value = false;
                        initUserForm(findForm);
                    } else {
                        ElMessage.error(res.message);
                    }
                });
            }
        } else {
            ElMessage.error('表单校验失败');
        }
    });
}
const deleteUserById = (data: any) => {
    deleteUser({ id: data.id }).then((res: any) => {
        if (res.code == 2000) {
            ElNotification({
                title: '成功',
                message: '删除成功',
                type: 'success',
            });
            initUserForm(findForm);
        } else {
            ElMessage.error(res.message);
        }
    });
}
// 表单验证
interface RuleForm {
    id: number
    avatarUrl: string,
    account: string,
    password: string,
    userName: string,
    job: string,
    roleId: string,
}

const ruleFormRef = ref<FormInstance>()
const userForm = reactive<RuleForm>({
    id: 0,
    avatarUrl: '',
    account: '',
    password: '',
    userName: '',
    job: '',
    roleId: '',
})

const rules = reactive<FormRules<RuleForm>>({
    avatarUrl: [
        { required: true, message: '请添加图片', trigger: 'blur' },
    ],
    account: [
        { required: true, message: '请添加账号（学号 || 工号）', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请添加密码', trigger: 'blur' },
    ],
    userName: [
        { required: true, message: '请添加用户名', trigger: 'blur' },
    ],
    job: [
        { required: true, message: '请添加工作单位', trigger: 'blur' },
    ],
    roleId: [
        { required: true, message: '请选择角色', trigger: 'blur' },
    ],
})
const handleFileUpload = (fileForm: any) => {
    console.log("_____" + fileForm.file)
    const fileData = new FormData();
    fileData.append('file', fileForm.file)
    fileData.append('userId', '1')
    Upload(fileData).then((res: any) => {
        if (res.code == 2000) {
            ElMessage.success(res.message)
            console.log(res)
            userForm.avatarUrl = res.data
        } else {
            ElMessage.error(res.message)
        }
    })
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    const validTypes = ['image/jpeg', 'image/png'];
    if (!validTypes.includes(rawFile.type)) {
        ElMessage.error('文件必须是 jpg 或 png 格式!');
        return false;
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('文件大小不能超过 2MB!');
        return false;
    }
    return true
}
// 时间格式化函数
const dataFormat = (data: any) => {
    return dayjs(data).format("YYYY-MM-DD HH:mm:ss");
}
</script>

<style scoped>
/* 上传图片 */
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
}
</style>